package util;

import hibernate.mappings.MsNode;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SocketUtil2 {
	private static int number = 8313;// 5857
	private static int CURMAX = 0;

	public String getDocumentAt(String urlString) {
		StringBuffer document = new StringBuffer();
		try {
			URL url = new URL(urlString);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "GB2312"));
			String line = null;
			while ((line = reader.readLine()) != null)
				document.append(line + "\n");
			reader.close();

		} catch (MalformedURLException e) {
			System.out.println("Unable to connect to URL: " + urlString);
		} catch (IOException e) {
			System.out.println("IOException when connecting to URL: "
					+ urlString);
		}
		return document.toString();
	}

	public String download(String num, String href) { // if(true)return 1;
		String dirpath="R:/2/";
		SocketUtil2 client = new SocketUtil2();
		String temp = client.getDocumentAt(href);
		int i1 = temp.indexOf("<ul class=\"file\">\n		<img src=\"");
		if (i1 > 0)
			temp = temp.substring(i1 + 30);
		else
			return "";
		i1 = temp.indexOf("alt=\"");
		String title = temp.substring(i1 + 5, temp.indexOf("\" />"));
		System.out.print("开始：" + num + title + href);
		i1 = temp.indexOf("01.jpg");
		temp = temp.substring(0, i1);
		File dir = new File(dirpath + num + title);
		if (!dir.exists())
			dir.mkdirs();
		// StringBuffer document = new StringBuffer();
		int i = 1;// http://img.rentiyishu.org/image/4623/11.jpg
		for (; i < 100; i++) {
			String tempurl = temp;
			if (i < 10)
				tempurl = tempurl + "0";
			tempurl = tempurl + i + ".jpg";
			URL url;
			try {

				// BufferedReader reader = new BufferedReader(new
				// InputStreamReader(
				// conn.getInputStream()));
				File file = new File(dirpath + num + title + "/" + title + i
						+ ".jpg");

				url = new URL(tempurl);
				// URLConnection conn = url.openConnection();
				InputStream in = url.openStream();
				BufferedInputStream bufIn = new BufferedInputStream(in);
				BufferedOutputStream bufOut = new BufferedOutputStream(
						new FileOutputStream(file));
				byte[] b = new byte[1];
				while (bufIn.read(b) != -1) {
					bufOut.write(b);
				}
				bufOut.flush();
				bufOut.close();
				bufIn.close();
				// System.out.println(file.length());
				if (file.length() == 69634l) {
					file.delete();
					break;
				}

			} catch (Exception e) {
				break;
			}
		}
		return title;

	}

	public void getList(Map<Integer, String> m, String str) {
		String strArray[] = str.split("</a></li><");
		String temp = "";
		int num = 0;
		String href = "";
		for (int i = 0; i < strArray.length; i++) {
			// System.out.println(strArray[i]);
			num = strArray[i].indexOf(".html");
			if (num < 0)
				continue;
			temp = strArray[i].substring(0, num);
			href = "http://www.rentiyishu.org/"
					+ temp.substring(temp.lastIndexOf("href=\"") + 6) + ".html";
			temp = temp.substring(temp.lastIndexOf("/") + 1);
			num = Integer.parseInt(temp);
			if (num > number) {
				// title = strArray[i].substring(strArray[i].lastIndexOf(">") +
				// 1);
				m.put(num, href);
				if (num > CURMAX) {
					CURMAX = num;
				}
			}

		}
	}

	public static void main(String[] args) {
		SocketUtil2 client = new SocketUtil2();
		String url = "http://www.rentiyishu.org/";
		String examda = client.getDocumentAt(url);
		Map<Integer, String> m = new HashMap<Integer, String>();
		examda = examda
				.substring(
						examda
								.indexOf("<li class=\"left\"><a href=\"shineirenti/\">室内人体</a></li>"),
						examda
								.indexOf("<li class=\"left\"><a href=\"oumeirenti/\">欧美人体</a></li>"));
		client.getList(m, examda);
		List<Integer> order = new ArrayList<Integer>();
		order.addAll(m.keySet());
		if (order.size() > 0) {
			Collections.sort(order);
			System.out.println("最大值是 " + CURMAX + "  总共：" + order.size());
		} else {
			System.out.println("no news!");
		}
		int num = 0;
		String href = "";
		for (int i = 0; i < order.size(); i++) {
			num = order.get(i);
			href = m.get(num);
			href = client.download(num + "", href);
			System.out.println("     ★完成 还有" + (order.size() - 1 - i));
		}
		// temp=examda
		// .substring(0,"");
		/*
		 * int number0 = number; int index = 0; List list = new ArrayList();
		 * String strArray[] = examda.split("<li><a"); int total =
		 * strArray.length; for (int i = 1; i < total; i++) {//
		 * /Images/2635.jpg" // alt="闲情逸致的模特心意" /> temp = strArray[i]; index =
		 * temp.indexOf("Photo"); int index2 = temp.indexOf(".jpg\" alt=\""); if
		 * (index > 0 && index2 > 0) { String num = temp.substring(index + 13,
		 * index2); int num0 = Integer.parseInt(num); if (num0 <= number) {
		 * continue; } if (num0 > number0) { number0 = num0; } String title =
		 * "notitle"; temp = temp.substring(index2 + 11); int index3 =
		 * temp.indexOf("\""); if (index3 > 0) title = temp.substring(0,
		 * index3); MsNode m = new MsNode(); m.setId(num0); m.setTitle(title);
		 * list.add(m); // int state = client.download(num, title); //
		 * System.out.println("完成：" + num + title+" 还有"+(total-i)); } }
		 * System.out.println("最大值是 " + number0 + " 总共：" + (total =
		 * list.size())); for (int i = 0; i < total; i++) { MsNode m = (MsNode)
		 * list.get(i); int num = m.getId(); String title = m.getTitle();
		 * client.download(num + "", title); System.out.println("完成：" + num +
		 * title + " 还有" + (total - i)); }
		 */
	}

}
